package servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.*;

@WebServlet(urlPatterns = "/m")
public class MajorServlet extends BaseServlet{
	static final int NUM = 3;
	public void page(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		List<College> colist;
		List<Major> maj;
		colist = DP.update(College.class,"select * from college" , null);
		maj = DP.update(Major.class, "select * from major", null);
		int len = maj.size();
		int pagenum = len%3==0?len/3:len/3+1;
		req.setAttribute("pagenum", pagenum);
		req.setAttribute("page", 1);
		req.setAttribute("colist", colist);
		maj = DP.update(Major.class, "select * from major limit 0,"+NUM, null);
		req.setAttribute("ma", maj);
		req.getRequestDispatcher("page/majorlist.jsp").forward(req, resp);
	}
	public void topage(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		List<College> colist;
		List<Major> maj;
		Integer pagenum = Integer.parseInt(req.getParameter("pagenum"));
		Integer page = Integer.parseInt(req.getParameter("page"));
		colist = DP.update(College.class,"select * from college" , null);
		String sql = "select * from major limit "+(page-1)*NUM+","+NUM;
		maj = DP.update(Major.class, sql, null);
		
		req.setAttribute("pagenum", pagenum);
		req.setAttribute("page", page);
		req.setAttribute("colist", colist);
		req.setAttribute("ma", maj);
		req.getRequestDispatcher("page/majorlist.jsp").forward(req, resp);
	}
	public void update(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		DP.update(Major.class, 
		"update major set c_id="+req.getParameter("cid")+" where id="+req.getParameter("id"), null);
	}
	public void insert(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		String sql = "insert into major(name,c_id) values(?,?)";
		DP.update(Major.class, sql, req.getParameter("name"),req.getParameter("cid"));
	}
	
}
